#include "plugin_pool.h"

plugin* plugin_pool::install_plugin(const string& _name,const string& _file, bool _used)
{
	plugin* tok = get_plugin(_name);
	if(!tok)
	{
		plugin*& t = m_plugins[_name];
		t = new plugin(_file);

		t->set_name(_name);
		t->set_used(_used);
		return t;
	}
	else
	{
		tok->set_used(_used);
	}
	return 0;
}

void plugin_pool::load_plugin(const string& _name)
{
	plugin* tok = get_plugin(_name);
	if(tok)
	{
		tok->set_used(true);
	}
}

void plugin_pool::unload_plugin(const string& name)
{
	plugin* tok = get_plugin(name);
	if(tok)
	{
		tok->set_used(false);
	}
}

plugin* plugin_pool::get_plugin(const string& name)
{
	plugin_map_iter ifind = m_plugins.find(name);
	if(ifind != m_plugins.end())
	{
		return ifind->second;
	}
	return 0;
}

void plugin_pool::destry()
{
	plugin_map_iter it_cur = m_plugins.begin();
	plugin_map_iter it_end = m_plugins.end();
	while(it_cur != it_end)
	{
		delete it_cur->second;
		it_cur++;
	}
}

void plugin_pool::read_json(jval& _root, list_entry_listener* _l)
{
	jmember* m_cur = _root.MemberBegin();
	jmember* m_end = _root.MemberEnd();

	while(m_cur != m_end)
	{
		string file = m_cur->name.GetString();
		int i = 0;
		string name = m_cur->value[i++].GetString();
		bool used = m_cur->value[i].GetBool();

		utf8_gbk(name);
		utf8_gbk(file);

		plugin*& t = m_plugins[name];
		t = new plugin(file);
		t->set_name(name);
		t->set_used(used);

		if(!_l->on_read_file_list(t))
		{
			delete t;
			m_plugins.erase(name);
		}

		m_cur++;
	}
}

void plugin_pool::write_json(jdoc& _doc, jval& _parent)
{
	plugin_map_iter p_cur = m_plugins.begin();
	plugin_map_iter p_end = m_plugins.end();

	while(p_cur != p_end)
	{
		string name_utf8 = p_cur->second->name();
		string file_utf8 = p_cur->second->file();
		gbk_utf8(name_utf8);
		gbk_utf8(file_utf8);

		jval plugin;
		plugin.SetArray();

		jval name, used;
		name.SetString(name_utf8.c_str(), _doc.GetAllocator());
		used.SetBool(p_cur->second->used());
		plugin.PushBack(name, _doc.GetAllocator());
		plugin.PushBack(used, _doc.GetAllocator());

		_parent.AddMember(file_utf8.c_str(), _doc.GetAllocator(), plugin, _doc.GetAllocator());

		p_cur++;
	}
}
